import { React, useRef, useState } from "react";
import Homehead from "../homehead/Homehead";
import "./User.css";
import img1 from "../../../assets/1.png";
import {
  Avatar,
  Form,
  Input,
  Button,
  Select,
  Radio,
  Checkbox,
  Row,
  Col,
  message,
} from "antd";
import { useDispatch, useSelector } from "react-redux";
import { updateUser } from "../../../store/userSlice";
import { useForm } from "antd/es/form/Form";
import { updatePic } from "../../../store/advatarSlice";

function User() {
  const [form] = useForm();
  const layout = {
    labelCol: {
      span: 8,
      offset: 0,
    },
    wrapperCol: {
      span: 12,
    },
  };
  const { user } = useSelector((state) => state.user);
  const { pic } = useSelector((state) => state.advatar);
  const fileInputRef = useRef();
  const dispatch = useDispatch();
  const [previewImg, setPreviewImg] = useState(img1);
  const { Option } = Select;
  const validateMessages = {
    required: "${label}是必填项!",
  };
  const [messageApi, contextHolder] = message.useMessage();

  // 对姓名的校验
  const validateName = (_, name) => {
    let reg = /^[\u4e00-\u9fa5]{2,15}$/;
    if (!reg.test(name)) {
      return Promise.reject(new Error("请输入2到15个汉字的姓名"));
    } else {
      return Promise.resolve();
    }
  };

  // 修改头像
  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        setPreviewImg(e.target.result);
        dispatch(updatePic(e.target.result));
      };
      reader.readAsDataURL(file);
    }
  };
// 点击按钮读取文件
  const setFileInputClicked = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  // 对表单进行验证
  const onCheck = () => {
    form
      .validateFields()
      .then((values) => {
        console.log(values);
      })
      .catch((error) => {
        messageApi.open({
          type: "error",
          content: "保存失败，请输入2到15个汉字的姓名！",
        });
      });
  };

  // 表单验证通过之后保存
  const onFinish = (values) => {
    dispatch(updateUser(values.user));
    messageApi.open({
      type: "success",
      content: "保存成功！",
    });
  };

  return (
    <div className="user">
      <div>
        {/* 顶部导航栏 */}
        <Homehead />
      </div>
      <div className="user-container">
        <div className="user-main">
          <div className="user-head">个人信息详情</div>
          <div className="user-info">
            {/* 用户头像 */}
            <div className="user-avatar">
              <Avatar
                size={{
                  xs: 24,
                  sm: 32,
                  md: 40,
                  lg: 64,
                  xl: 80,
                  xxl: 100,
                }}
                style={{ marginTop: "20px" }}
                src={pic}
              />
              <input
                type="file"
                ref={fileInputRef}
                accept="image/*"
                style={{ display: "none" }}
                onChange={handleFileChange}
              ></input>
              <Button
                type="primary"
                onClick={setFileInputClicked}
                style={{ marginTop: "20px" }}
              >
                添加/更换头像
              </Button>
            </div>
            {/* 用户的个人信息表单 */}
            <Form
              {...layout}
              form={form}
              name="nest-messages"
              onFinish={onFinish}
              style={{
                maxWidth: 600,
              }}
              validateMessages={validateMessages}
            >
              <Form.Item
                name={["user", "name"]}
                label="姓名"
                rules={[
                  {
                    required: true,
                    validator: validateName,
                  },
                ]}
                initialValue={user.name}
              >
                <Input />
              </Form.Item>
              <Form.Item label="省份">
                <Form.Item
                  name={["user", "province"]}
                  noStyle
                  rules={[
                    {
                      required: true,
                      message: "省份是必填项",
                    },
                  ]}
                  initialValue={user.province}
                >
                  <Select placeholder="选择省份">
                    <Option value="Beijing">北京</Option>
                    <Option value="Shanghai">上海</Option>
                  </Select>
                </Form.Item>
              </Form.Item>
              <Form.Item
                label="性别"
                name={["user", "sex"]}
                initialValue={user.sex}
              >
                <Radio.Group>
                  <Radio value="man"> 男 </Radio>
                  <Radio value="female"> 女</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                name={["user", "residence"]}
                label="常住地"
                initialValue={user.residence}
              >
                <Checkbox.Group>
                  <Row>
                    <Col span={12}>
                      <Checkbox
                        value="北京"
                        style={{
                          lineHeight: "32px",
                        }}
                      >
                        北京
                      </Checkbox>
                    </Col>
                    <Col span={12}>
                      <Checkbox
                        value="上海"
                        style={{
                          lineHeight: "32px",
                        }}
                      >
                        上海
                      </Checkbox>
                    </Col>
                  </Row>
                </Checkbox.Group>
              </Form.Item>
              <Form.Item
                name={["user", "notes"]}
                label="备注"
                initialValue={user.notes}
              >
                <Input.TextArea />
              </Form.Item>
              {contextHolder}
              <Form.Item
                wrapperCol={{
                  ...layout.wrapperCol,
                  offset: 8,
                }}
              >
                <Button type="primary" htmlType="submit" onClick={onCheck}>
                  保存
                </Button>
                <Button
                  style={{
                    marginLeft: "10px",
                    background: "orange",
                    color: "#fff",
                  }}
                >
                  {" "}
                  取消
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
}

export default User;
